package me.zhengjie.stock.pipeline;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.zhengjie.stock.domain.TblKline;
import me.zhengjie.stock.service.TblKlineService;
import org.springframework.stereotype.Component;
import us.codecraft.webmagic.ResultItems;
import us.codecraft.webmagic.Task;
import us.codecraft.webmagic.pipeline.Pipeline;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * 获取当天（最后交易日）K线数据处理
 */
@Slf4j
@Component
@AllArgsConstructor
public class KlineTodayPipeline implements Pipeline {

    private final TblKlineService klineService;

    @Override
    public void process(ResultItems resultItems, Task task) {
        try {
            if (resultItems.isSkip()) {
                return;
            }
            JSONArray dataList = resultItems.get("dataList");
            if (dataList != null && !dataList.isEmpty()) {
                int size = dataList.size();
                List<TblKline> tblKlineList = new ArrayList<>();
                for (int i = 0; i < size; i++) {
                    JSONObject tblKlineJson = dataList.getJSONObject(i);
                    if (!(tblKlineJson.get("f17") instanceof BigDecimal)) {
                        //还未上市或已退市，获取不到价格直接跳过
                        continue;
                    }
                    TblKline tblKline = toObject(tblKlineJson);
                    String name = tblKline.getName();
                    String code = tblKline.getName();
                    if (name.contains("PT") || name.contains("ST") || name.endsWith("退")) {
                        //ST、退市等股票设置为0
                        continue;
                    }
                    if (code.startsWith("30") || code.startsWith("688") || code.startsWith("43") || code.startsWith("83")) {
                        //创业板股票||北交所
                        continue;
                    }
                    LambdaQueryWrapper<TblKline> queryWrapper = new LambdaQueryWrapper<>();
                    queryWrapper.eq(TblKline::getCode, tblKline.getCode());
                    queryWrapper.eq(TblKline::getName, tblKline.getName());
                    queryWrapper.eq(TblKline::getTradingDate, tblKline.getTradingDate());
                    TblKline klineDb = klineService.getOne(queryWrapper);
                    if (klineDb != null) {
                        tblKline.setId(klineDb.getId());
                        klineService.updateById(tblKline);
                        log.info("save TradingDateKlinePipeline to db fail! code:{}, name:{} exited", tblKline.getCode(), tblKline.getName());
                        continue;
                    }
                    tblKlineList.add(tblKline);
                    //保存数据
                    log.info("save TradingDateKlinePipeline to db success! code:{}, name:{}", tblKline.getCode(), tblKline.getName());
                }
                klineService.saveBatch(tblKlineList);
                log.info("save TradingDateKlinePipeline to Mysql success! size:{}", size);
            }
        } catch (Exception e) {
            log.info("TradingDateKlinePipeline error:{}", e);
        }
    }

    private TblKline toObject(JSONObject dataJson) {
        log.info("TradingDateKlinePipeline toObject dataJson:{}", dataJson);
        TblKline kline = new TblKline();
        kline.setClosingPrice(dataJson.getBigDecimal("f2"));
        kline.setChangeRate(dataJson.getBigDecimal("f3"));
        kline.setChangeAmount(dataJson.getBigDecimal("f4"));
        kline.setTradingVolume(dataJson.getInteger("f5"));
        kline.setTradingAmount(dataJson.getBigDecimal("f6"));
        kline.setAmplitudeRate(dataJson.getBigDecimal("f7"));
        kline.setTurnoverRate(dataJson.getBigDecimal("f8"));
        kline.setCode(dataJson.getString("f12"));
        kline.setName(dataJson.getString("f14"));
        kline.setPeakPrice(dataJson.getBigDecimal("f15"));
        kline.setBottomPrice(dataJson.getBigDecimal("f16"));
        kline.setOpeningPrice(dataJson.getBigDecimal("f17"));
        Long time = dataJson.getLong("f124");
        Calendar calendar = new Calendar.Builder().setInstant(time * 1000).build();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String tradingDate = sdf.format(calendar.getTime());
        kline.setTradingDate(tradingDate);
        kline.setGmtCreate(new Date());
        kline.setGmtModified(new Date());
        return kline;
    }
}



